package com.talent.service.iot.mqtt.handler;

import com.talent.service.iot.mqtt.model.request.TlMqttPubCompReq;
import com.talent.service.iot.mqtt.model.request.TlMqttPubRelReq;
import com.talent.service.iot.mqtt.model.variable.TlMqttPubRelVariableHead;
import com.talent.service.iot.mqtt.service.IMqttMsgService;
import com.talent.service.iot.mqtt.service.IMqttSessionService;
import com.talent.service.iot.mqtt.service.IMqttSubscriptionService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


/**
 * @Author: hszhou
 * @Date: 2024/12/5 9:46
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@ChannelHandler.Sharable
@Component
public class TlMqttPubRelHandler extends SimpleChannelInboundHandler<TlMqttPubRelReq> {

    private static final Logger logger = LoggerFactory.getLogger(TlMqttPubRelHandler.class);


    private final IMqttMsgService msgService;

    private final IMqttSubscriptionService subscriptionService;

    private final IMqttSessionService sessionService;

    public TlMqttPubRelHandler(IMqttSubscriptionService subscriptionService,IMqttMsgService msgService,IMqttSessionService sessionService){
        this.msgService =msgService;
        this.subscriptionService = subscriptionService;
        this.sessionService = sessionService;
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TlMqttPubRelReq req) throws Exception {
        logger.debug("in【PUBREL】 handler");

        //根据这个消息获取到对应的
        TlMqttPubRelVariableHead variableHead = req.getVariableHead();
        Integer messageId = variableHead.getMessageId();
        logger.debug("【BROKER】 2. receive rel messageId is 【{}】",messageId);

        //表示已经收到过这个消息了 可以移除掉这个消息ID了
        TlMqttPublishHandler.qos2PacketIds.remove(messageId);
        logger.debug("【BROKER】 3. remove pub messageId is 【{}】",messageId);

        //Channel channel = ctx.channel();
      //  String clientId = channel.attr(AttributeKey.valueOf(Constant.CLIENT_ID)).get().toString();

        //这里是服务器收到了客户端的PUBREL消息 说明客户端已经收到了服务器给他发送的rec消息 客户端可以删除自己的publish消息了 不必重发
        //msgService.clearPublishMessage(clientId,messageId);
        //向客户端发送comp消息
        sendComp(messageId,ctx);


    }

    /**
     * 发送comp消息给客户端 表示broker已经收到了消息
     * @param messageId 消息ID
     * @param ctx 通道
     */
    private void sendComp(int messageId,ChannelHandlerContext ctx){

        TlMqttPubCompReq res = TlMqttPubCompReq.of(messageId);
        ctx.channel().writeAndFlush(res);
    }


}
